package com.babel.util.str;

import com.babel.util.CalculateUtil;
import com.babel.util.tools.DateTools;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.apache.commons.lang.StringUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil extends StringUtils{
	private static final char[] PASSWORD_KEYS = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

	public static boolean isNumber(String str){
		if(str == null || str.equals("")){
			return false;
		}
		return str.matches("[0-9]+");
	}

    public static String hideNickname(String nickname){
        if(nickname==null){
            return "";
        }
        int start=0;
        int end=0;
        if(nickname.length()>10){
            start=3;
            end=nickname.length()-4;
        }else if(nickname.length()>6){
            start=2;
            end=nickname.length()-3;
        }else if(nickname.length()>1){
            start=1;
            end=nickname.length()/2;
        }else {
            return "*";
        }

        StringBuffer sb=new StringBuffer();
        for (int i=0;i<nickname.length();i++){
            if(i>=start&&i<=end){
                sb.append("*");
            }else{
                sb.append(nickname.charAt(i));
            }
        }
        return  sb.toString();
    }
    public static String hideNickname(String nickname,int start,int end){
        if(StrUtil.isEmpty(nickname)){
            return "";
        }
        if(nickname.length()<start||nickname.length()<end){
            return "";
        }
        if(end<start){
            return  "";
        }
        StringBuffer sb=new StringBuffer();
        for (int i=0;i<nickname.length();i++){
            if(i>=start&&i<=end){
                sb.append("*");
            }else{
                sb.append(nickname.charAt(i));
            }
        }
        return  sb.toString();
    }

    public static String hideFormatStr(String str, int showStartLength,int showEndLength){
        if(StrUtil.isEmpty(str)){
            return "";
        }
        if(str.length() <= showStartLength+showEndLength){
            return str;
        }
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<str.length(); i++){
            if(i>=showStartLength && i<= str.length()-showEndLength-1){
                sb.append("*");
            }else{
                sb.append(str.charAt(i));
            }
        }
        return  sb.toString();
    }

    public static String hideFormatStr(String str, int showStartLength,int showEndLength,String appendStr){
        if(StrUtil.isEmpty(str)){
            return "";
        }
        if(str.length() <= showStartLength+showEndLength){
            return str;
        }
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<str.length(); i++){
            if(i>=showStartLength && i<= str.length()-showEndLength-1){
            	sb.append("*");
            }else{
                sb.append(str.charAt(i));
            }
        }
        sb.replace(sb.indexOf("*"),sb.lastIndexOf("*")+1 , appendStr);
        return  sb.toString();
    }

    public static String toTrim(String str) {
    	if(str == null) {
    		return "";
    	}
    	return str.trim();
    }

    public static String toStr(Object object) {
    	if(object == null) {
    		return "";
    	}
    	return object.toString();
    }

	public static String doubleToString(Double value) {
		if (value == null) {
			return "";
		}
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		df.setMaximumFractionDigits(2);
		df.applyPattern("0.00");
		return df.format(value);
	}

    public static long toLong(Object obj) {
    	if(obj == null) {
    		return -1;
    	}
    	try {
    		return Long.parseLong(obj.toString());
    	} catch (Exception e) {
    		return -1;
    	}
    }
    public static int toInt(Object obj) {
    	if(obj == null) {
    		return -1;
    	}
    	try {
    		return Integer.parseInt(obj.toString());
    	} catch (Exception e) {
    		return -1;
    	}
    }

    public static double toDouble(Object obj) {
    	if(obj == null) {
    		return 00.00;
    	}
    	try {
    		return Double.parseDouble(obj.toString());
    	} catch (Exception e) {
    		return 00.00;
    	}
    }

    public static boolean isNotNull(String str) {
    	if(str == null) {
    		return false;
    	}
    	if("".equals(str.trim())) {
    		return false;
    	}
    	return true;
    }

    public static String repStr(String content, Map<String, String> map) {
    	if(!StrUtil.isNotNull(content) || map == null || map.isEmpty()) {
    		return content;
    	}
		String reg;
		Set<String> set = map.keySet();
		for(String key : set) {
			reg = key.replaceAll("\\$", "\\\\\\$");
			String value = map.get(key);
			if(value==null){
				value="";
			}
            if(value.contains("$")){
                value.contains("无效的值，包含特殊字符$");
            }
			content = content.replaceAll(reg, value);
		}
		return content;
	}

    public static String subSuffix(String str, int index) {
		if(StrUtil.isNotNull(str) && str.length() >= index) {
			str = str.substring(str.length() - index, str.length());
			return str;
		}
		return "";
	}

    public static Map<String, String> getLoanPhaseMapValue(Map<?, ?> map) {
		Map<String, String> m = new HashMap<String, String>();
		String biddate = StrUtil.toStr(map.get("create_time"));
		if(StrUtil.isNotNull(biddate)) {
			m.put("$biddate$", DateTools.dateToString(DateTools.stringToDate(biddate, DateTools.DATE_PATTERN_DAY)));
		}
		m.put("$loantitle$", StrUtil.toStr(map.get("loan_title")));
		m.put("$amount$", StrUtil.toStr(map.get("total_lend_amount")));
		double principal = StrUtil.toDouble(map.get("already_repay_principal"));
		double interest = StrUtil.toDouble(map.get("already_repay_interest"));
		m.put("$principal$", (CalculateUtil.doubleAdd(principal,2)) + "");
		m.put("$interest$", (CalculateUtil.doubleAdd(interest,2)) + "");
		m.put("$revenue$", (CalculateUtil.doubleAdd(principal,interest,2)) + "");
		String nowrepaydate = StrUtil.toStr(map.get("realy_repay_date"));
		if(StrUtil.isNotNull(nowrepaydate)) {
			m.put("$nowrepaydate$", DateTools.dateToString(DateTools.stringToDate(nowrepaydate, DateTools.DATE_PATTERN_DAY)));
		}
		String nextrepaydate = StrUtil.toStr(map.get("repay_date"));
		if(StrUtil.isNotNull(nowrepaydate)) {
			m.put("$nextrepaydate$", DateTools.getFrontMonthDate(nextrepaydate, 1));
		}
		return m;
	}

    public static String getRandomCode(){
    	String s = UUID.randomUUID().toString();
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
    }

    /**
     * @Title: getIds
     * @Description: 根据传入的逗号分隔的ID字符串，返回一个ID数组,在批量更新时用到
     * @param @param ids
     * @param @return    设定文件
     * @return Object[]    返回类型
     * @throws
     */
     public static Object[] getIds(String ids){
     	if (StringUtils.isNotBlank(ids)) {
 			String[] idList = ids.split(",");
 			Object[] intIds = new Integer[idList.length];
 			int i = 0;
 			for (String id : idList) {
 				if (StringUtils.isNotBlank(id)) {
 					intIds[i++] = Integer.parseInt(id);
 				}
 			}
 			return intIds;
 		}
     	return null;
     }

     /**
      * 获取一个字符串中所有的数字
      * @param str
      * @return
      */
     public static String getNumberInStr(String str){
     	if(str.isEmpty()){
     		return "";
     	}
     	String [] split = str.split("[\\D]+");
     	if(split.length == 0){
     		return "";
     	}
     	StringBuilder sb = new StringBuilder() ;
     	for(String s:split){
     		sb.append(s);
     	}
     	return sb.toString();
     }

     /***
      * 银行卡格式化，并隐藏
      * @param input : 银行卡号,例如input="6225880137706868"
      * @param  startShow   起始显示的位数
      * @param  endShow     最后显示的位数
      *                     formBankCard(input,4,3)-->6225 **** **** *868
      * @return
      */
     public static String formBankCard(String input,int startShow,int endShow){
         if(StrUtil.isEmpty(input)){
             return "";
         }
         input=input.replaceAll("([\\d]{4})(?=\\d)", "$1 ");
         if(input.length() < startShow || input.length() < endShow){
             return input;
         }
         StringBuilder sb = new StringBuilder();
         for (int i=0; i<input.length(); i++){
             if(i>startShow && i<(input.length()-endShow) && ((i+1)%5)!=0){
                 sb.append("*");
             }else{
                 sb.append(input.charAt(i));
             }
         }
         return sb.toString();
     }

 	/**
 	 * html转化成字符串
 	 * @param htmlString
 	 * @return
 	 */
 	public static String htmlToStr(String htmlString){
 		if(isNotNull(htmlString)){
 			return htmlString.replaceAll("<", "&lt").replaceAll(">", "&gt").replaceAll("\"", "&quot");
 		}else{
 			return "";
 		}

 	}

 	/**
 	 * 字符串转化成html
 	 * @param htmlString
 	 * @return
 	 */
 	public static String strTohtml(String htmlString){
 		if(isNotNull(htmlString)){
 			return htmlString.replaceAll("&lt","<").replaceAll("&gt",">").replaceAll("&quot","\"");
 		}else{
 			return "";
 		}

 	}

 	/**
 	 * 返回中文的首字母
 	 * @param str
 	 * @return
 	 */
 	public static String getPinYinHeadChar(String str) {
 		String convert = "";
 		for (int j = 0; j < str.length(); j++) {
 			char word = str.charAt(j);
 			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
 			if (pinyinArray != null) {
 				convert += pinyinArray[0].charAt(0);
 			} else {
 				convert += word;
 			}
 		}
 		return convert;
 	}

 	public static String listToString(List<String> stringList){
         StringBuilder StringBuilder = new StringBuilder();
         if(stringList != null && !stringList.isEmpty()){
             for(int index =0;index < stringList.size();index++){
                 String indexStr = stringList.get(index);
                 if(StrUtil.isNotNull(indexStr)){
                     if(index < stringList.size()-1){
                         StringBuilder.append(indexStr+",");
                     }else{
                         StringBuilder.append(indexStr);
                     }
                 }
             }
         }
         return StringBuilder.toString();
     }

 	public static String integerToString(List<Integer> integerList){
 		StringBuilder StringBuilder = new StringBuilder();
 		if(integerList != null && !integerList.isEmpty()){
 			for(int index =0;index < integerList.size();index++){
 				Integer indexStr = integerList.get(index);
 				if(indexStr != null){
 					if(index < integerList.size()-1){
 						StringBuilder.append(indexStr+",");
 					}else{
 						StringBuilder.append(indexStr);
 					}
 				}
 			}
 		}
 		return StringBuilder.toString();
 	}

 	public static String listToStringWithQuote(List<String> stringList){
         StringBuilder str = new StringBuilder();
         if(stringList != null && !stringList.isEmpty()){
             for(int index =0;index < stringList.size();index++){
                 String indexStr = stringList.get(index);
                 if(StrUtil.isNotNull(indexStr)){
                 	str.append("'").append(indexStr).append("',");
                 }
             }
             if(str.length()>0){
             	str.setLength(str.lastIndexOf(","));
             }
         }
         return str.toString();
     }
     /**
      *
      * @Title: hideBankCard
      * @Description: TODO(隐藏银行卡方法，只显示前4后4位)
      * @param @param 银行卡号
      * @param @return    设定文件
      * @return String    返回类型
      * @throws
      */
 	public static String hideBankCard(String bankCard){
 		if(StrUtil.isEmpty(bankCard)){
 			return "";
 		}
 		int cardLength=bankCard.length();
 		StringBuilder sb = new StringBuilder();
 		int start=4;
 		int end =cardLength-5;
 		for(int i=0;i<bankCard.length();i++){
 			if(i>=start && i<=end){
 				sb.append("*");
 			}else{
 				sb.append(bankCard.charAt(i));
 			}
 		}
 		return sb.toString();
 	}

	/**
	 * 隐藏银行卡方法，只显示后4位
	 * @param cardNumber
	 * @return
	 */
	public static String hideBankCard2(String cardNumber) {
		if (isNull(cardNumber)) {
			return "";
		}
		cardNumber = trim(cardNumber);
		char[] chars = cardNumber.toCharArray();
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < chars.length; i++) {
			if (i % 4 == 0) {
				builder.append(" ");
			}
			if (i < chars.length - 4) {
				builder.append("*");
			} else {
				builder.append(chars[i]);
			}
		}
		return builder.toString();
	}
 	/**
 	 *
 	 * @Title: hideMobile
 	 * @Description: TODO(隐藏手机号方法，只显示前3后4位)
 	 */
 	public static String hideMobile(String mobile){
 		if(StrUtil.isEmpty(mobile)){
 			return "";
 		}
 		int cardLength=mobile.length();
 		StringBuilder sb = new StringBuilder();
 		int start=3;
 		int end =cardLength-5;
 		for(int i=0;i<mobile.length();i++){
 			if(i>=start && i<=end){
 				sb.append("*");
 			}else{
 				sb.append(mobile.charAt(i));
 			}
 		}
 		return sb.toString();
 	}

 	/**
 	 *
 	 * @Title: hideMobile
 	 * @Description: TODO(隐藏身份证方法，只显示前3后4位)
 	 */
 	public static String hideIdCard(String idCard){
 		if(StrUtil.isEmpty(idCard)){
 			return "";
 		}
 		int cardLength=idCard.length();
 		StringBuilder sb = new StringBuilder();
 		int start=3;
 		int end =cardLength-5;
 		for(int i=0;i<idCard.length();i++){
 			if(i>=start && i<=end){
 				sb.append("*");
 			}else{
 				sb.append(idCard.charAt(i));
 			}
 		}
 		return sb.toString();
 	}

 	/**
 	 * 判断字符串是否包含中文
 	 * @param str
 	 * @return
 	 */
 	public static boolean isContainChinese(String str) {
 		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
 		Matcher m = p.matcher(str);
 		if (m.find()) {
 			return true;
 		}
 		return false;
 	}
 	/**
      * 读取字符串第i次出现特定符号的位置
      * @param string
      * @param i
      * @return
      */
     public static int getCharacterPosition(String string ,int i,String character){
         Matcher slashMatcher = Pattern.compile(character).matcher(string);
         int mIdx = 0;
         while(slashMatcher.find()) {
            mIdx++;
            //当"/"符号第三次出现的位置
            if(mIdx == i){
               break;
            }
         }
         return slashMatcher.start();
      }

     /**
 	 * 把app版本号转换为整数类型方便判断 默认及异常返回-1
 	 * @param version
 	 * @return
 	 */
 	public static int convertAppVersionToDigit(String version) {
 		int aversion = -1;
 		if(isNotNull(version)){
 			version = version.replaceAll("\\.", "");
         	try {
         		aversion = Integer.parseInt(version);
     		  } catch (NumberFormatException e) {
     		  }
         }
 		return aversion;
 	}

 	public static List<String>  stringToList(String ids){
 		List<String> list = new ArrayList<>();
 		if(isNotNull(ids)){
 			for(String id : ids.split(",")){
 				list.add(id);
 			}
 		}
 		return list;
 	}

 	public static boolean isMobileNO(String mobiles) {
 		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
 		Matcher m = p.matcher(mobiles);
 		return m.matches();
 	}

 	public static boolean isNull(String str) {
 		if (null == str || str.equalsIgnoreCase("null") || str.equals("")) {
 			return true;
 		} else {
 			return false;
 		}
 	}

	/**
	 * 按照正则替换指定字符
	 * @param str 替换str
	 * @param map  需要替换的内容
	 * @return  String
	 * @auther  杨康
	 */
	public static String replaceStr(String str ,Map<String,String> map) {
		for (Map.Entry<String, String> entry : map.entrySet()) {
			str = Pattern.compile("\\$\\{" + entry.getKey() + "}").matcher(str).replaceAll(entry.getValue()==null?"":entry.getValue());
		}
		return str;
	}

	//生成8位随机密码
	public static String randomPassword() {
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 8; i++) {
			int r = random.nextInt(PASSWORD_KEYS.length);
			sb.append(PASSWORD_KEYS[r]);
		}
		return sb.toString();
	}

	public static String getSex(String idNum){
		String sex = idNum.substring(16, 17);
		if(Integer.parseInt(sex)%2==0){
			sex = "女";
		}else{
			sex ="男";
		}
		return sex;
	}
	
    public static boolean checkUserHasAuth(List<Map<String, Object>> authList, int authId) {
    	boolean flag = false;
    	if (null != authList && authList.size() > 0) {
        	for (Map<String, Object> authMap : authList) {
				if (!isNull(authMap.get("id").toString())) {
					if (Integer.parseInt(authMap.get("id").toString()) == authId) {
						flag = true;
						break;
					}
				}
			}
        }
    	return flag;
    }
    
    /**
     * 计算字符串长度（中文、字母、数字）
     * @param value
     * @return
     */
    public static int String_length(String value) {
    	int valueLength = 0;
    	String chinese = "[\u4e00-\u9fa5]";
    	for (int i = 0; i < value.length(); i++) {
    		String temp = value.substring(i, i + 1);
    		if (temp.matches(chinese)) {
    			valueLength += 2;
    		} else {
    			valueLength += 1;
    		}
    	}
    	return valueLength;
    }
}